import time
from concurrent.futures import thread
from http import HTTPStatus

import requests
import json

import shutil
import os
import io

import dashscope

def get_url(url):
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return json.loads(response.text)
    else:
        print(f"请求失败，原因：{response.text}")
        return None

def call_with_messages(file_url):
    plugins = {'pdf_extracter': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': '你作为一个经验丰富的软件工程师'},
                {'role': 'user', 'content': [
                    {'text': '从10个维度出发，给这篇文章打分，重点考虑这篇文章的格式规范，结构清晰度、语言表达、信息完整性、逻辑连贯性及专业性等，每个10分共100分。'},
                    {'file': file_url}]
                 }]
    response = dashscope.Generation.call(
        api_key="sk-87c1cbb4dbcb4323a2e6785150439b14",
        model='qwen-turbo',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    if response.status_code == HTTPStatus.OK:
        print(response)

    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))
    return response


# 语雀API的Base URL和端点
base_url = "https://se2024.yuque.com/api/v2/"

# 你的认证信息，比如Token或其他认证方式
headers = {
    "X-Auth-Token": "daUnVbO1WzxhSiIo8bo2wkP2rKbDxjYpz0KD2Vy9",
    "Content-Type": "application/json",
    "X-Csrf-Token": "ouY6csTu-22dcyWS1M1vzyMS",
    "Referer": "https://se2024.yuque.com/org-wiki-se2024-go4lg1/kmyk33/pf0wupluuld8lho9",
    "Cookie": "lang=zh-cn; lang=zh-cn; _yuque_session=GjmDSBKgdOqFpJrwqFMTeWLU4LEwORq57qqJ7crdBU1MCD-jzhr9Yvf_T6TZ2yTtBfjg06Ftuz9fNFzNpxGJ_Q==; receive-cookie-deprecation=1; yuque_ctoken=ouY6csTu-22dcyWS1M1vzyMS; aliyungf_tc=81255cf344f0aaf1e715cf854371814804ed307fd930d9195a1fe70ee3d3a544; current_theme=default; acw_tc=ac11000117206336754746802e6df6c159ddd9de5fb189bfc8fa903aa98482"
}
wiki_url = "https://se2024.yuque.com/api/modules/org_wiki/wiki/show?organizationId=21006641"
# 获得公共空间的数据
wiki_info = get_url(wiki_url)
# 获得公共空间的个人实验报告知识库列表
personal_book_data = wiki_info["layouts"][0]['placements'][0]['blocks'][1]['data'][2]['books']
book_id_dict = {}
for book in personal_book_data:
    book_id_dict[book['name']] = {}
    book_id_dict[book['name']]['id'] = book['id']
    book_id_dict[book['name']]['slug'] = book['slug']
    book_id_dict[book['name']]['user_id'] = book['user_id']
    book_id_dict[book['name']]['user'] = book['user']
temp_book = book_id_dict['实验2~报告收集知识库']
# 获取文档列表
doc_list_url = "https://se2024.yuque.com/api/docs?book_id=" + str(temp_book['id'])
doc_list_response = get_url(doc_list_url)
doc_list = doc_list_response["data"]
for temp_doc in doc_list:
    # 判断在/first 文件夹下是否有该文件
    if os.path.exists("./first/" + str(temp_doc["id"]) + ".pdf"):
        print(temp_doc["title"] + "开始使用通义进行评价==================================")

        doc_id = temp_doc["id"]
        file_url = 'https://gitee.com/jjyu-keji/experiment_pdf/raw/master/first/'+str(doc_id)+'.pdf'
        comment_response=call_with_messages(file_url)
        comment=comment_response.output.choices[0].message.content
        comment_data = {
            "commentable_type": "Doc",
            "commentable_id": doc_id,
            "body": comment
        }
        comment_url = "https://se2024.yuque.com/api/comments"
        comment_over_response = requests.post(comment_url, headers=headers, data=json.dumps(comment_data))

        # 检状判断
        if comment_over_response.status_code == 200:
            # 评论完后打印评论结果，并等5秒后，开启下一次评论
            print(comment_over_response.text)
            print(temp_doc["title"] + "评论成功创建======================")
            time.sleep(5)


        else:
            print(f"失败，原因：{comment_over_response.text}")
    else:
        print(temp_doc["title"] + "  文件不存在，无法评价==================================")
        continue






# 构造评论数据
# 请根据API要求构造数据结构，可能包括评论内容、文档ID、作者等
data = {
    "doc_id": "目标文档ID", "content": "这是来自API创建的评论", "user_id": "评论者ID"}
# 用户信息
user_url = base_url + "user"
user_info = get_url(user_url)

login_id = user_info["data"]["login"]
# 获取用户的知识库列表
repo_list_url = base_url + "groups/" + login_id + "/repos"
repo_list = get_url(repo_list_url)
book_list = repo_list["data"]
book_id = book_list[0]["id"]
# 获取文档列表
doc_list_url = base_url + "repos/" + str(book_id) + "/docs"
doc_list_response = get_url(doc_list_url)
doc_list = doc_list_response["data"]
doc_id = doc_list[0]["id"]
# 获取文档详情
doc_detail_url = base_url + "repos/" + str(book_id) + "/docs/" + str(doc_id)
doc_detail_response = get_url(doc_detail_url)

'''
创建评论
POST /comments

任何人可以使用，需要认证

Parameters
Key	Description
commentable_type	见获取列表说明
commentable_id	见获取列表说明
body	评论内容
parent_id	如果需要对一条评论进行回复，这里传那个评论的编号，否则不传
'''
# 创建评论
comment_headers = {
    "X-Auth-Token": "daUnVbO1WzxhSiIo8bo2wkP2rKbDxjYpz0KD2Vy9",
    "Content-Type": "application/json",
    "X-Csrf-Token": "ouY6csTu-22dcyWS1M1vzyMS",
    "Referer": "https://se2024.yuque.com/nfr0sf/cf_records/ze3x0u",
    "Cookie": "lang=zh-cn; lang=zh-cn; _yuque_session=GjmDSBKgdOqFpJrwqFMTeWLU4LEwORq57qqJ7crdBU1MCD-jzhr9Yvf_T6TZ2yTtBfjg06Ftuz9fNFzNpxGJ_Q==; receive-cookie-deprecation=1; yuque_ctoken=ouY6csTu-22dcyWS1M1vzyMS; aliyungf_tc=81255cf344f0aaf1e715cf854371814804ed307fd930d9195a1fe70ee3d3a544; current_theme=default"
}


# https://se2024.yuque.com/api/docs/cg78tfk5pzawrmeu?book_id=48515198&include_contributors=true&include_like=true&include_hits=true&merge_dynamic_data=false
